package cn.tedu.medicalmanagementsystem.base.interceptors;

import cn.tedu.medicalmanagementsystem.base.utils.JwtUtils;
import cn.tedu.medicalmanagementsystem.base.utils.UserContext;
import io.jsonwebtoken.Claims;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@Slf4j
public class JwtInterceptor implements HandlerInterceptor {
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        if (request.getMethod().equals("OPTIONS")) {
            response.setStatus(HttpServletResponse.SC_OK);
            return true;
            // 如果不是，我们就把token拿到，用来做判断
        }else {


            // 获取请求头中的token
            String token = request.getHeader("authorization");
            log.debug("获取到令牌：{}", token);
            // 调用JwtUtils中的方法，进行解析
            try {
                Claims claims = JwtUtils.parseJWT("medical-management-system", token);
                Long userId = ((Number) claims.get("escortId")).longValue();
                UserContext.setCurrentUser(userId);
                log.info("用户ID：{}", userId);
            } catch (Exception e) {
                response.setStatus(401);
                // 抛出异常，请求终止
                throw new RuntimeException(e);
            }
        }
        // 解析成功，放行
        return true;
    }
}
